package com.leetcode.No1834;

import org.junit.Test;

import java.util.*;

public class Solution {
    public int[] getOrder(int[][] tasks) {
        Map<int[], Integer> map = new HashMap<>();
        for (int i = 0; i < tasks.length; i++) {
            map.put(tasks[i], i);
        }
        Arrays.sort(tasks, Comparator.comparingInt(t -> t[0]));
        TreeSet<int[]> set = new TreeSet<>((t1, t2) -> {
            if (t1[1] != t2[1]) {
                return t1[1] - t2[1];
            } else {
                return map.get(t1) - map.get(t2);
            }
        });
        int resultIdx = 0;
        int[] result = new int[tasks.length];
        int time = tasks[0][0];
        int i = 0;
        while (i < tasks.length || !set.isEmpty()) {
            while (i < tasks.length && tasks[i][0] <= time) {
                set.add(tasks[i++]);
            }
            if (set.size() == 0) {
                time = tasks[i][0];
                continue;
            }
            int[] task = set.pollFirst();
            result[resultIdx++] = map.get(task);
            time += task[1];
        }
        return result;
    }

    @Test
    public void test() {
//        int[][] tasks = {{1,2},{2,4},{3,2},{4,1}};
//        int[][] tasks = {{19,13},{16,9},{21,10},{32,25},{37,4},{49,24},{2,15},{38,41},{37,34},{33,6},{45,4},{18,18},{46,39},{12,24}};
//        int[][] tasks = {{23,40},{10,32},{12,18},{10,39},{25,4},{18,12},{38,18},{36,1},{26,5},{45,35},{5,43},{19,19},{46,41},{25,22},{29,17},{26,33},{49,45},{43,44},{50,2}};
//        int[][] tasks = {{19,13},{16,9},{21,10},{32,25},{37,4},{49,24},{2,15},{38,41},{37,34},{33,6},{45,4},{18,18},{46,39},{12,24}};
//        int[][] tasks = {{5,2},{7,2},{9,4},{6,3},{5,10},{1,1}};
        int[][] tasks = {{5,2}, {7,2}, {9,4}, {6,3}, {5,10}, {1,1}};
        System.out.println(Arrays.toString(getOrder(tasks)));
    }
}
